package com.example.demo.service;

import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

//    @Autowired
//    private MilvusService milvusService;

    private final Random random = new Random();

    @Transactional
    public User registerUser(String username, String email, String password) {
        if (userRepository.existsByUsername(username)) {
            throw new RuntimeException("Username is already taken!");
        }

        if (userRepository.existsByEmail(email)) {
            throw new RuntimeException("Email is already in use!");
        }

        User user = new User();
        user.setUsername(username);
        user.setEmail(email);
        user.setPassword(passwordEncoder.encode(password));
        user.setRoles(Collections.singleton("USER"));
        user.setIsActive(true);
        user.setBirthdate(new Date());
        User savedUser = userRepository.save(user);
        // 为用户生成随机向量并存储到Milvus
       // List<Float> randomVector = generateRandomVector(128);
       //  milvusService.insertVector(savedUser.getId(), randomVector);
        return savedUser;
    }

//    public List<User> findSimilarUsers(Long userId, int count) {
//        User user = userRepository.findById(userId)
//                .orElseThrow(() -> new RuntimeException("User not found"));
//
//        // 这里假设我们已经有了用户的向量，实际应用中可能需要从某处获取
//        // 这里简单地生成一个随机向量用于演示
//        List<Float> userVector = generateRandomVector(128);
//
//        // 使用Milvus查找相似向量
//        List<Long> similarUserIds = milvusService.searchSimilarVectors(userVector, count);
//
//        // 获取相似用户的详细信息
//        return similarUserIds.stream()
//                .map(id -> userRepository.findById(id))
//                .filter(Optional::isPresent)
//                .map(Optional::get)
//                .collect(Collectors.toList());
//    }

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    public Optional<User> getUserById(Long id) {
        return userRepository.findById(id);
    }

    public Optional<User> getUserByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    // 分页获取用户列表
    public org.springframework.data.domain.Page<User> getAllUsers(org.springframework.data.domain.Pageable pageable) {
        return userRepository.findAll(pageable);
    }

    // 分页+过滤获取用户列表
    public org.springframework.data.domain.Page<User> getUsersByFilters(String username, String email, Boolean isActive, org.springframework.data.domain.Pageable pageable) {
        return userRepository.findByFilters(username, email, isActive, pageable);
    }

    @Transactional
    public User updateUser(User user) {
        // 检查用户是否存在
        User existingUser = userRepository.findById(user.getId())
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        // 更新用户信息，保留原有密码（如果未提供新密码）
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            existingUser.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        
        // 更新其他字段
        if (user.getUsername() != null) {
            existingUser.setUsername(user.getUsername());
        }
        if (user.getEmail() != null) {
            existingUser.setEmail(user.getEmail());
        }
        if (user.getRoles() != null) {
            existingUser.setRoles(user.getRoles());
        }
        if (user.getBirthdate() != null) {
            existingUser.setBirthdate(user.getBirthdate());
        }
        if (user.getIsActive() != null) {
            existingUser.setIsActive(user.getIsActive());
        }
        
        // 保存并返回更新后的用户
        return userRepository.save(existingUser);
    }

    @Transactional
    public User toggleUserStatus(Long userId, Boolean isActive) {
        // 检查用户是否存在
        User existingUser = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        // 更新用户状态
        existingUser.setIsActive(isActive);
        
        // 保存并返回更新后的用户
        return userRepository.save(existingUser);
    }

    private List<Float> generateRandomVector(int dimension) {
        List<Float> vector = new java.util.ArrayList<>(dimension);
        for (int i = 0; i < dimension; i++) {
            vector.add(random.nextFloat());
        }
        return vector;
    }
}
